package com.iqik.base.zk.api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateSession implements Watcher {
    public static CountDownLatch countDownLatch = new CountDownLatch(1);

    /**
     * 回调方法
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        // TODO
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            // 解除主程序阻塞
            countDownLatch.countDown();
            System.out.println("建立连接");
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        /**
         * 客户端创建一个zk实例来连接服务
         * new ZooKeeper(connectString, sessionTimeOut, Watcher)
         * 参数依次：
         *  1。IP:PORT
         *  2.5000ms
         *  3.监听器（当特定事件除法监听时，zk会通过watcher通知客户端）
         */
        ZooKeeper zooKeeper = new ZooKeeper("132.232.16.135:2181", 5000, new CreateSession());
        // 连接时是个异步的
        System.out.println(zooKeeper.getState());
        // 计数工具类，让main处于等待状态
        countDownLatch.await();
    }
}
